<?php
/**
 * Description:laravel图片上传处理类
 *
 * project: larabbs03
 * Date: 2019/4/14/20:53
 */

namespace Utility\library\images;

use Intervention\Image\ImageManagerStatic as image;

class ImageUpload
{
    protected $storeConf = 'public';

    /*
     * 初始化filesystes.php配置中的磁盘设置,默认为public
     */
    public function __construct(string $config = '')
    {
        $this->setDisk($config);
    }

    //图片上传
    public function upload($file, $floder, $prefiex, $height = null)
    {
        if (!$file->isValid()) {
            return false;
        }
        $storeDir = $floder . '/' . date("Y/m/d", time());
        $extend = $file->getClientOriginalExtension();
        $fileName = $prefiex . "_" . time() . "_" . str_random(10) . '.' . $extend;

        $path = $file->storeAs($storeDir, $fileName, $this->storeConf);
        $dataPath = "/storage/" . $path;
        $realPath = $this->getDiskRoot() . '/' . $storeDir . '/' . $fileName;
        if ($height) {
            $this->clip($realPath, $height);
        }
        //dataPath是相对于public的路径
        return ['path' => $dataPath];
    }

    //进行图片压缩
    protected function clip($imagePath, $height)
    {
        $img = image::make($imagePath);
        $img->resize($height, null, function ($constraint) {
            $constraint->aspectRatio();
            $constraint->upsize();
        });
        $img->save();
    }

    //设置存储磁盘
    protected function setDisk($config)
    {
        $disks = config('filesystems.disks');
        if (array_key_exists($config, $disks)) {
            $this->storeConf = $config;
        }
    }

    //获取指定disk的绝对路径
    protected function getDiskRoot()
    {
        $disks = config('filesystems.disks');
        if (array_key_exists($this->storeConf, $disks)) {
            return $disks[$this->storeConf]['root'];
        }
    }

}
